package xyz.acproject.danmuji.tools;

import xyz.acproject.danmuji.conf.set.AIReplySetConf;
import xyz.acproject.danmuji.utils.OkHttp3Utils;
import okhttp3.Response;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class AIAutoReplyTools {
    // DeepSeek API
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-3c8cbb19b83a48baba1696d55b445009"; // TODO: 替换为你的API Key
    
    // 回复风格模板
    private static final String[] REPLY_STYLES = {
        "可爱萌系", "温暖治愈", "幽默风趣", "元气满满", "温柔贴心"
    };
    
    // 默认回复长度限制（字符数）
    private static final int DEFAULT_MAX_REPLY_LENGTH = 50;
    
    // 默认敏感词过滤
    private static final String[] DEFAULT_SENSITIVE_WORDS = {
        "破站", "b站", "bilibili", "B站", "BILIBILI", "直播", "主播", "观众", "粉丝"
    };

    /**
     * 获取AI生成的回复内容
     * @param prompt 用户互动内容（如送礼、关注、弹幕）
     * @return AI生成的回复
     */
    public static String getAIReply(String prompt) {
        return getAIReply(prompt, "default", null);
    }
    
    /**
     * 获取AI生成的回复内容（指定类型）
     * @param prompt 用户互动内容
     * @param type 回复类型：danmu(弹幕), gift(礼物), follow(关注), welcome(欢迎)
     * @return AI生成的回复
     */
    public static String getAIReply(String prompt, String type) {
        return getAIReply(prompt, type, null);
    }
    
    /**
     * 获取AI生成的回复内容（带配置）
     * @param prompt 用户互动内容
     * @param type 回复类型
     * @param config AI回复配置
     * @return AI生成的回复
     */
    public static String getAIReply(String prompt, String type, AIReplySetConf config) {
        // 检查配置是否开启AI回复
        if (config != null && !config.is_open_ai_reply()) {
            return "";
        }
        
        try {
            String style = getReplyStyle(config);
            int maxLength = getMaxLength(config);
            String[] sensitiveWords = getSensitiveWords(config);
            
            String systemPrompt = buildSystemPrompt(type, style, maxLength, config);
            
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + API_KEY);
            headers.put("Content-Type", "application/json");
            
            String json = "{"
                    + "\"model\": \"deepseek-chat\","
                    + "\"messages\": ["
                    + "{\"role\": \"system\", \"content\": \"" + escapeJson(systemPrompt) + "\"},"
                    + "{\"role\": \"user\", \"content\": \"" + escapeJson(prompt) + "\"}"
                    + "],"
                    + "\"max_tokens\": 100,"
                    + "\"temperature\": 0.7"
                    + "}";
                    
            Response response = OkHttp3Utils.getHttp3Utils().httpPostJson(API_URL, headers, json);
            if (response != null && response.body() != null) {
                String responseBody = response.body().string();
                String aiReply = parseResponse(responseBody);
                return filterAndFormatReply(aiReply, maxLength, sensitiveWords, config);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDefaultReply(type);
    }
    
    /**
     * 获取回复风格
     */
    private static String getReplyStyle(AIReplySetConf config) {
        if (config != null && !"auto".equals(config.getAIReplyStyle())) {
            return config.getAIReplyStyle();
        }
        return REPLY_STYLES[new Random().nextInt(REPLY_STYLES.length)];
    }
    
    /**
     * 获取最大长度
     */
    private static int getMaxLength(AIReplySetConf config) {
        if (config != null && config.getMax_reply_length() > 0) {
            return config.getMax_reply_length();
        }
        return DEFAULT_MAX_REPLY_LENGTH;
    }
    
    /**
     * 获取敏感词列表
     */
    private static String[] getSensitiveWords(AIReplySetConf config) {
        if (config != null && config.isEnableSensitiveFilter()) {
            String[] customWords = config.getCustomSensitiveWords();
            String[] allWords = new String[DEFAULT_SENSITIVE_WORDS.length + customWords.length];
            System.arraycopy(DEFAULT_SENSITIVE_WORDS, 0, allWords, 0, DEFAULT_SENSITIVE_WORDS.length);
            System.arraycopy(customWords, 0, allWords, DEFAULT_SENSITIVE_WORDS.length, customWords.length);
            return allWords;
        }
        return DEFAULT_SENSITIVE_WORDS;
    }
    
    /**
     * 构建系统提示词
     */
    private static String buildSystemPrompt(String type, String style, int maxLength, AIReplySetConf config) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个" + style + "风格的直播助手，负责回复直播间互动。");
        prompt.append("要求：1.回复简洁有趣，不超过" + maxLength + "字；");
        prompt.append("2.避免敏感词汇；3.保持" + style + "风格；");
        
        if (config != null && config.isEnableEmoji()) {
            prompt.append("4.使用emoji表情增加趣味性；");
        }
        
        prompt.append("5.直接回复内容，不要加前缀。");
        
        switch (type) {
            case "danmu":
                prompt.append("用户发送了弹幕，请用" + style + "风格回复。");
                break;
            case "gift":
                prompt.append("用户送了礼物，请用" + style + "风格表示感谢。");
                break;
            case "follow":
                prompt.append("用户关注了直播间，请用" + style + "风格表示感谢。");
                break;
            case "welcome":
                prompt.append("用户进入直播间，请用" + style + "风格表示欢迎。");
                break;
            default:
                prompt.append("请用" + style + "风格回复用户互动。");
        }
        
        return prompt.toString();
    }
    
    /**
     * 解析API响应
     */
    private static String parseResponse(String responseBody) {
        try {
            int idx = responseBody.indexOf("\"content\":");
            if (idx != -1) {
                int start = responseBody.indexOf('"', idx + 10) + 1;
                int end = responseBody.indexOf('"', start);
                if (start > 0 && end > start) {
                    return responseBody.substring(start, end);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 过滤和格式化回复
     */
    private static String filterAndFormatReply(String reply, int maxLength, String[] sensitiveWords, AIReplySetConf config) {
        if (reply == null || reply.trim().isEmpty()) {
            return "";
        }
        
        // 过滤敏感词
        String filteredReply = reply;
        if (config == null || config.isEnableSensitiveFilter()) {
            for (String word : sensitiveWords) {
                filteredReply = filteredReply.replace(word, "***");
            }
        }
        
        // 限制长度
        if (filteredReply.length() > maxLength) {
            filteredReply = filteredReply.substring(0, maxLength - 3) + "...";
        }
        
        // 清理多余空格和换行
        filteredReply = filteredReply.replaceAll("\\s+", " ").trim();
        
        return filteredReply;
    }
    
    /**
     * 获取默认回复
     */
    private static String getDefaultReply(String type) {
        switch (type) {
            case "danmu":
                return "谢谢你的弹幕～";
            case "gift":
                return "感谢你的礼物！";
            case "follow":
                return "感谢关注！";
            case "welcome":
                return "欢迎来到直播间！";
            default:
                return "感谢你的支持！";
        }
    }

    // 简单转义JSON字符串
    private static String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }
} 